package cn.tedu.ivos.dictoption.service.impl;

import cn.tedu.ivos.base.exception.ServiceException;
import cn.tedu.ivos.base.response.StatusCode;
import cn.tedu.ivos.dict.mapper.DictMapper;
import cn.tedu.ivos.dict.pojo.dto.DictQuery;
import cn.tedu.ivos.dict.pojo.vo.DictVO;
import cn.tedu.ivos.dictoption.mapper.DictOptionMapper;
import cn.tedu.ivos.dictoption.pojo.dto.DictOptionQuery;
import cn.tedu.ivos.dictoption.pojo.dto.DictOptionSaveParam;
import cn.tedu.ivos.dictoption.pojo.entity.DictOption;
import cn.tedu.ivos.dictoption.pojo.vo.DictOptionVO;
import cn.tedu.ivos.dictoption.service.DictOptionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class DictOptionServiceImpl implements DictOptionService {
    @Autowired
    DictOptionMapper dictOptionMapper;
    @Autowired
    DictMapper dictMapper;
    @Override
    public List<DictOptionVO> selectDictO(DictOptionQuery dictOptionQuery) {
        log.debug("查询字典选项业务：{}",dictOptionQuery);
        List<DictOptionVO> list=dictOptionMapper.selectDictO(dictOptionQuery);
        return list;
    }

    @Override
    public void saveDictO(DictOptionSaveParam dictOptionSaveParam) {
        log.debug("保存字典选项业务：{}",dictOptionSaveParam);
        DictOption  dictOption=new DictOption();
        BeanUtils.copyProperties(dictOptionSaveParam,dictOption);
        if(dictOption.getId()==null){
            dictOption.setCreateTime(new Date());
            dictOptionMapper.insertDictO(dictOption);
        }else {
            dictOption.setUpdateTime(new Date());
            dictOptionMapper.updateDictO(dictOption);
        }
    }

    @Override
    public void deleteDictO(Long id) {
        log.debug("删除字典选项参数：{}",id);
        dictOptionMapper.deleteDictO(id);
        log.debug("删除字典选项完成");
    }

    @Override
    public List<DictOptionVO> selectDictOByCode(String code) {
        log.debug("根据字典code查询字典项业务：{}",code);
        //需要现根据字典code查询字典VO查出来
        DictQuery dictQuery=new DictQuery();
        dictQuery.setCode(code);
        List<DictVO> dictVOList=dictMapper.selectDict(dictQuery);
        if (dictVOList!=null&&dictVOList.size()>0){
            DictVO  dictVO=dictVOList.get(0);
            //进一步查询字典项
            DictOptionQuery dictOptionQuery=new DictOptionQuery();
            dictOptionQuery.setDictId(dictVO.getId());
            List<DictOptionVO> list=dictOptionMapper.selectDictO(dictOptionQuery);
            return list;
        }else {
            throw new ServiceException(StatusCode.DATA_UNEXISTS);
        }
    }
}
